package com.cwx.web.admin;

import com.cwx.pojo.User;
import com.cwx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String toLoginPage(){
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        RedirectAttributes redirectAttributes,
                        Model model){
        User user = userService.CheckUser(username, password);

        if (user != null){
            user.setPassword("null");
            session.setAttribute("user",user);
            model.addAttribute("user",user);
            return "admin/index";
        }else {
            redirectAttributes.addFlashAttribute("msg","用户名或者密码错误");
            //重定向就要使用重定向的  model中设置的数据只会携带在转发中 所以重定向到的请求传递数据就要用到RedirectAttributes
            return "redirect:/admin";
        }
    }

    @GetMapping("/loginout")
    public String loginOut(HttpSession session){
        session.invalidate();   //注销session
        return "redirect:/admin";
    }

}
